#include "PDFManager.h"

void errorHandler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void *user_data) {
    printf("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no,
           (HPDF_UINT)detail_no);
}

PDFManager::PDFManager() {
    pdf_ = HPDF_New(errorHandler, nullptr);
    if (!pdf_) {
        throw std::runtime_error("failed to initalize PDF");
    }

    HPDF_SetCompressionMode(pdf_, HPDF_COMP_ALL);
    HPDF_UseUTFEncodings(pdf_);
    // HPDF_SetCurrentEncoder(pdf_, "UTF-8");
}

PDFManager::~PDFManager() {
    if (pdf_) {
        HPDF_Free(pdf_);
    }
}

/**
 * 加载字体
 */
void PDFManager::loadFont(const char *font_path) {
    auto fontname = HPDF_LoadTTFontFromFile(pdf_, font_path, HPDF_TRUE);
    if (!fontname) {
        throw std::runtime_error("failed to load font");
    }

    font_ = HPDF_GetFont(pdf_, fontname, "UTF-8");
    if (!font_) {
        std::cout << "Failed to get font object for: " << font_path << std::endl;
        throw std::runtime_error("Failed to get font object");
    }
}

/**
 * 写入文字
 */
#include <codecvt>
#include <locale>

void PDFManager::addTextPage(const std::wstring &text, size_t start_index, size_t chars_per_page) {
    HPDF_Page page = HPDF_AddPage(pdf_);
    HPDF_Page_SetFontAndSize(page, font_, 12);
    HPDF_Page_SetWidth(page, PAGE_WIDTH);
    HPDF_Page_SetHeight(page, PAGE_HEIGHT);

    float x = MARGIN_X;
    float y = MARGIN_Y;

    // 创建 UTF-8 转换器
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;

    for (int line = 0; line < LINES_PER_PAGE; line++) {
        if (start_index >= text.size())
            break;

        std::wstring line_text = text.substr(start_index, CHARS_PER_LINE);
        std::string line_utf8 = converter.to_bytes(line_text); // 转换为 UTF-8
        HPDF_Page_BeginText(page);
        HPDF_Page_TextOut(page, x, y, line_utf8.c_str());
        HPDF_Page_EndText(page);

        // 换行
        start_index += CHARS_PER_LINE;
        y -= LINE_SPACING;
    }
}

void PDFManager::saveToFile(const char *file_name) {
    HPDF_SaveToFile(pdf_, file_name);
}
